/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.cmd;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.Command;
import com.foreveross.bsl.Config;
import com.foreveross.bsl.PushMessage;
import com.foreveross.bsl.push.MessageParams;
import com.foreveross.bsl.push.PushClient;
import com.foreveross.bsl.push.ReceiverTypeEnum;
import com.google.common.collect.Maps;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-12-11
 *
 */
public class PushRequestCmd implements Command {
	
	private static final Logger log = LoggerFactory.getLogger(PushRequestCmd.class);
	private Config config;
	private PushClient pc;
	private int repeat=1;
	
	public PushRequestCmd(Config config, String sessionKey){
		this.config=config;
		this.pc=new PushClient(config.getProperty("push.url", true));
		this.pc.setSessionKey(sessionKey);
	}
	
	@Override
	public void execute() {
		try {
			pc.push(buildMsgParams(this.getMsg()), repeat);
		} catch (Exception e) {
			log.error("push request error!", e);
		}
	}
	
	private MessageParams buildMsgParams(String msg){
		MessageParams mp=new MessageParams();
		mp.setAppId(this.getAppId());
		mp.setReceiverType(ReceiverTypeEnum.TAG);
		Map<String, String> tags=Maps.newHashMap();
		tags.put("platform", "push-test");
		mp.setTags(tags);
		mp.setReceiverValue(this.getReceiverValue());
		mp.setMessage(new PushMessage(msg));
		return mp;
	}
	
	public String getAppId(){
		return this.config.getProperty("push.appId", true);
	}

	public String getMsg(){
		return this.config.getProperty("push.n.msg", "test push");
	}
	
	public ReceiverTypeEnum getReceiverTypeEnum(){
		ReceiverTypeEnum type=ReceiverTypeEnum.valueOf(this.config.getProperty("push.n.receiverType", true));
		if(!ReceiverTypeEnum.APP_ID.equals(type) && !ReceiverTypeEnum.DEVICE_ID.equals(type)){
			throw new IllegalArgumentException("现只支持APP_ID,DEVICE_ID方式");
		}
		return type;
	}
	
	public String getReceiverValue(){
		return this.config.getProperty("push.n.receiverValue");
	}

	/**
	 * @return the repeat
	 */
	public int getRepeat() {
		return repeat;
	}

	/**
	 * @param repeat the repeat to set
	 */
	public void setRepeat(int repeat) {
		this.repeat = repeat;
	}
}
